<?php
namespace app\index\controller;
use RecursiveArrayIterator;
//迭代器类
use RecursiveIteratorIterator;
//迭代器类
use think\Controller;
use AlibabaCloud\Client\AlibabaCloud;
//阿里巴巴SDk
use think\Db;
use think\Model;
class Index extends Controller {
    public function index() {
        $array=$this->config();
        return $this->fetch('',['zdurl'=>$array]);
    }

    


    public function config() {
        $array=[
            [
                'zdUrl'=>'',//站点Url
                'site_id'=>'',//百度统计站点id
                'AccessKey'=>'',//阿里云秘钥
                'AccessKeySecret'=>'',//阿里云身份验证
                "username"=>"",//百度账户
                "password"=>"",//百度密码
                "token"=>"",//秘钥
                'RegionId'=>''//阿里云服务器地区
            ],
            [
                'zdUrl'=>'',
                'site_id'=>'',
                'AccessKey'=>'',
                'AccessKeySecret'=>'',
                "username"=>"",
                "password"=>"",
                "token"=>"",
                'RegionId'=>''
            ],
        ];
        return $array;
    }
    //判断当前查询的是哪个站点
    public function pd($zdurl) {
        $Array=$this->config();
        for ($i=0;$i<count($Array);$i++) {
            if ($Array[$i]['zdUrl']==$zdurl) {
                $configArray=$Array[$i];
            }
        }
        return $configArray;
    }
    //查询时间获取
    public function time($StartTime,$EndTime) {
        date_default_timezone_set('PRC');  //设置时间为标准时间

        $time1=strtotime($StartTime);
        $time2=strtotime($EndTime);

        $StartTime=date('Y-m-d H:i:s',$time1);   //正常时间用作前台显示

        $EndTime=date('Y-m-d H:i:s',$time2);

        //百度统计时间
        $bdStartTime=date('Ymd',$time1);  //百度查询格式的开始时间,格式为例如2022年6月1日，那么就是20220601

        $bdEndTime=date('Ymd',$time2); //百度查询格式的结束时间

        //阿里云时间
        date_default_timezone_set('UTC');//设置时间为utc

        $UtcStartTime=date('Y-m-d\TH:i:s\Z',$time1);  //阿里云的查询时间,时间转换成yyyy-MM-ddTHH:mm:ssZ格式

        $UtcEndTime=date('Y-m-d\TH:i:s\Z',$time2);
        //将前端页面显示、百度、与阿里云所需要的时间格式装入数组返回
        $timeArray=['bdStartTime'=>$bdStartTime,'bdEndTime'=>$bdEndTime,'UtcStartTime'=>$UtcStartTime,'UtcEndTime'=>$UtcEndTime,'StartTime'=>$StartTime,'EndTime'=>$EndTime];
        return $timeArray;
    }

    //阿里云cnd错误率查询
    public function alyfx($startTime,$endTime,$url,$key,$KeySecret,$RegionId) {
        $AccessKey=$key; //阿里标识,获取地址https://help.aliyun.com/document_detail/140411.html

        $AccessKeySecret=$KeySecret;  //身份验证

        AlibabaCloud::accessKeyClient($AccessKey, $AccessKeySecret)
            ->regionId($RegionId)
            ->asDefaultClient();
        $result = AlibabaCloud::rpc()
            ->product('Cdn')
            ->version('2018-05-10')
            ->action('DescribeDomainSrcHttpCodeData')
            ->method('POST')
            ->host('cdn.aliyuncs.com')
            ->options([
                'query' => [
                    'RegionId' => $RegionId,//服务器地区
                    'DomainName' => $url,//查询站点
                    'StartTime' => $startTime,//开始时间
                    'EndTime' => $endTime,//结束时间
                    'Interval' => "3600",//查询时间粒度
                ],
            ])
            ->request();
        $array=$result->toArray();
        $long=count($array['HttpCodeData']['UsageData']);
        //value数组长度
        $arraySum=[];
        //创建一个求和数组,计算请求总次数
        global $erreo;
        //声明全局变量
        for ($i=0;$i<$long;$i++) {
            $codeArray=array_column($array['HttpCodeData']['UsageData'][$i]['Value']['CodeProportionData'],'Count');
            $arraySum[$i]=array_sum($codeArray);
            //先算出每个codeArray数组中的和，在赋值给新的数组。
            $CodeArray=$array['HttpCodeData']['UsageData'][$i]['Value']['CodeProportionData'];
            //CodeProportionData数组
            $longs=count($array['HttpCodeData']['UsageData'][$i]['Value']['CodeProportionData']);
            //CodeProportionData数组长度;
            for ($j=0;$j<$longs;$j++) {
                if ($CodeArray[$j]['Code']>=500) {
                    //如果当前状态码大于500，那么输出当前请求次数
                    $erreo+=$CodeArray[$j]['Count'];
                    //将code大于500的状态码累加求和
                }
            }
        }
        $CountSum=array_sum($arraySum);
        //所有请求总次数
        $cwl=(($erreo/$CountSum)*100);
        //$cdncwl=(floor($cwl*100)/100).'%';//不进行4舍五入
        $cdncwl=(round($cwl,2)).'%';//进行4舍五入
        return $cdncwl;
    }
    //百度统计uv、pv、ip、访问时长、跳出率查询
    public function bdtj($startTime,$endTime,$username,$password,$token,$site_id) {
        $array=[
            "header"=>[
                "username"=>$username,//百度账户
                "password"=>$password,//百度密码
                "token"=>$token,//秘钥
                "account_type"=>1
            ],
            "body"=>[
                "site_id"=>$site_id,//站点id
                "start_date"=>$startTime,//开始时间
                "end_date"=>$endTime,//结束时间
                "metrics"=>"pv_count,visitor_count,ip_count,bounce_ratio,avg_visit_time",
                "method"=>"source/all/a"
            ]
        ];
        $apiUrl='https://api.baidu.com/json/tongji/v1/ReportService/getData';
       $returnArray=$this->posturl($apiUrl,$array);
        $array=$returnArray['body']['data'][0]['result']['pageSum'][0];
        $ValueArray=[];
        foreach ($array as $key=>$value){
            $ValueArray[$key]=$value;

        }
        $bdzrss=$returnArray['body']['data'][0]['result']['items'][1][4][2];
        array_push($ValueArray,$bdzrss);
        return $ValueArray;


    }
    //百度收录查询
    public function bdsl($url) {
        $u='https://res.abeim.cn/api-baidu_entry?url='.$url;
        //api请求地址
        $returnArray=$this->geturl($u);
        return $returnArray['data'];
        //输出收录量
        if ($returnArray['msg']!='ok') {
            $returnArray['data']=$returnArray['msg'];
        }
    }
    public function bdqz($url) {
        $u='https://apistore.aizhan.com/baidurank/siteinfos/[8d1809880c4547f3173357d3817c17c4]?domains='.$url;
        //api请求地址
        $returnArray=$this->geturl($u);
        $arrayiter = new RecursiveArrayIterator($returnArray);
        //不是很理解这两个内置的迭代器，反正大概功能就是把多维数组变成一个一维数组方便操作，
        //如果没有key的话，将一个多维数组打散成一个数组没有key对应的不太方便操作，建议有key——value这种数组使用。
        $iteriter = new RecursiveIteratorIterator($arrayiter);
        global $pc,$m,$ip;
        foreach ($iteriter as $key => $val) {
            switch ($key) {
                case 'pc_br';
                    $pc=$val;
                    break;
                case 'm_br';
                    $m=$val;
                    break;
                case 'ip';
                    $ip=$val;
            }
        }
        $qzArray= ['pc'=>$pc,'m'=>$m,'ip'=>$ip];
        return $qzArray;
    }
    //数据存储
    public function inster() {
        $TimeArray=[];
        $Array=[];
        $zdUrl=input('post.zdUrl');
        //获取查询站点Url;
        $StartTime=input('post.StartTime');
        //接收表单提交开始时间
        $EndTime=input('post.EndTime');
        //接收表单提交结束时间
        $submit=input('post.s');
        //接收到操作类型
        $configArray=$this->pd($zdUrl);
        if ($submit=='查询并删除历史查询记录') {
            Db::table('show')->where('1=1')->delete();
        }
        $TimeArray=$this->time($StartTime,$EndTime);
        $showStartTime=$TimeArray['StartTime'];
        //页面显示时间
        $showEndTime=$TimeArray['EndTime'];
        //页面显示时间
        $CdnCwl=$this->alyfx($TimeArray['UtcStartTime'],$TimeArray['UtcEndTime'],$configArray['zdUrl'],$configArray['AccessKey'],$configArray['AccessKeySecret'],$configArray['RegionId']);
        //Cdn错误率
        $bdtjArray=$this->bdtj($TimeArray['bdStartTime'],$TimeArray['bdEndTime'],$configArray['username'],$configArray['password'],$configArray['token'],$configArray['site_id']);
        //百度统计uv、pv、ip、访问时长、跳出率、百度自然搜索流量
        $bdslNum=$this->bdsl($configArray['zdUrl']);
        //百度收录量
        $qzArray=$this->bdqz($configArray['zdUrl']);
        //站点pc权重、站点m权重、IP预计来路
        $countArray=['zdUrl'=>$zdUrl,
            'StartTime'=>$showStartTime,
            'EndTime'=>$showEndTime,
            'CdnCwl'=>$CdnCwl,
            'uv'=>$bdtjArray[1],
            'pv'=>$bdtjArray[0],
            'ip'=>$bdtjArray[2],
            'tcl'=>$bdtjArray[3]."%",
            'fwsc'=>$bdtjArray[4]."s",
            'bdzrss'=>$bdtjArray[5],
            'pcqz'=>$qzArray['pc'],
            'mqz'=>$qzArray['m'],
            'ipll'=>$qzArray['ip'],
            'sl'=>$bdslNum
        ];
        $result=Db::table('show')->insert($countArray);
        return $this->fetch('show');
    }
    //数据呈现
    public function show() {
        $select=Db::table('show')->select();
        $Array=['code'=>0,'msg'=>'','count'=>count($select),'data'=>$select];
        return json($Array);
    }
    //模拟post请求
    public  function posturl($url,$data) {
        $data  = json_encode($data);
        $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output,true);
    }
    //模拟get请求
    public  function geturl($url) {
        $headerArray =array("Content-type:application/json;","Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $outputs = json_decode($output,true);
        return $outputs;
    }
}